package com.linln.admin.pcs.controller;


import com.linln.admin.config.IDCardEncryptor;
import com.linln.admin.system.service.AppService;
import com.linln.common.data.QuerySpec;
import com.linln.common.utils.ValidationUtil;
import com.linln.component.actionLog.annotation.EntityParam;
import com.linln.modules.system.domain.Company;
import com.linln.modules.system.domain.Porter;
import com.linln.modules.system.domain.Project;
import com.linln.modules.system.repository.CompanyRepository;
import com.linln.modules.system.repository.PorterRepository;
import com.linln.modules.system.repository.ProjectRepository;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;


/**
 * 陪护公司管理
 */
@Controller
@RequestMapping("/pcs/company")
public class CompanyController {

    @Autowired
    private AppService appService;
    @Autowired
    private  ProjectRepository projectRepository;
    @Autowired
    private CompanyRepository companyRepository;
    @Autowired
    private PorterRepository porterRepository;



    /**
     * 陪护公司页面
     */
    @GetMapping("/index")
    @RequiresPermissions("pcs:company:index")
    public ResponseEntity<?> index(Model model, @EntityParam Company company) {
        return appService.layTable(companyRepository, before -> {
                    // 添加模板变量
                    return model;

                },

                after -> {
                    QuerySpec querySpec = QuerySpec.matching();
                    querySpec.withMatcher("name", QuerySpec.LIKE)
                            .withMatcher("code", QuerySpec.LIKE)
                            .withMatcher("legalName", QuerySpec.LIKE)
                            .withMatcher("legalPhone", QuerySpec.LIKE)
                            .withMatcher("addr", QuerySpec.LIKE);
                    return QuerySpec.of(querySpec);
                },

                "/pcs/company/index",

                (pageResult) -> {
                    // 在这里处理 pageResult
                    pageResult.getContent().forEach(item -> {
                        Company data = (Company) item;
                        try {
                            data.setLegalPhone(IDCardEncryptor.aesTuoMinPhoneDecrypt(data.getLegalPhone()));
                            data.setLegalCardNo(IDCardEncryptor.aesTuoMinDecrypt(data.getLegalCardNo()));

                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }

                        QuerySpec querySpec = QuerySpec.matching();
                        querySpec.withMatcherValue("companyId", QuerySpec.EQUAL, String.valueOf(data.getId()))
                                .withMatcherValue("status", QuerySpec.EQUAL, String.valueOf(1));
                        Specification<Porter> specification = QuerySpec.of(querySpec);
                        data.setPorterNum(porterRepository.count(specification));
                        //item = data;
                    });
                }

        );

    }


    /**
     * 表单
     */
    @RequestMapping("/form")
    @RequiresPermissions("pcs:company:add")
    public ResponseEntity<?> form(Model model, @EntityParam Company company) throws Exception {

        return appService.form(companyRepository, "/pcs/company/form",
                (isEdit) -> {

                    return model;

                },
                (isEdit, vo) -> {
                    Company c = (Company) vo;
                    try {
                        c.setLegalPhone(IDCardEncryptor.aesDecrypt(c.getLegalPhone()));
                        c.setLegalCardNo(IDCardEncryptor.aesDecrypt(c.getLegalCardNo()));
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    model.addAttribute("vo", c);
                    // 你可以在这里添加其他逻辑
                    return model;
                },
                (data) -> {
                    // 保存前数据校验
                    List<ValidationUtil.ValidationRule<?>> rules = new ArrayList<>();
                    // 添加邮箱的校验规则
                    //            rules.add(new ValidationUtil.ValidationRule<>(
                    //                    porter.getCardNo(),
                    //                    email -> email != null ,
                    //                    "Email格式不正确"
                    //            ));

                    // 执行校验
                    return ValidationUtil.validateFields(rules);

                },
                (data) -> {

                    // 数据处理
                    if(company.getId() != null){
                        Company origin = companyRepository.getById(company.getId());
                        company.setStatus(origin.getStatus());
                        company.setCreateUser(origin.getCreateUser());
                        company.setCreateTime(origin.getCreateTime());
                    }
                    company.setStatus((byte) 1);
                    try {
                        company.setLegalPhone(IDCardEncryptor.aesEncrypt(company.getLegalPhone()));
                        company.setLegalCardNo(IDCardEncryptor.aesEncrypt(company.getLegalCardNo()));
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    return company;
                },

                (data) -> {
                    // 保存后续逻辑在这写
                });

    }



    /**
     * 修改状态
     * @param model
     * @param project
     * @return
     * @throws Exception
     */
    @RequestMapping("/state")
    @RequiresPermissions("pcs:company:state")
    public ResponseEntity<?> state(Model model, @EntityParam Project project) throws Exception {

        return appService.save(projectRepository, (data) -> {

            // 校验数据
            return ValidationUtil.validateFields(new ArrayList<>());

        }, (data) -> {
            // 处理数据
            Project origin = projectRepository.getById(project.getId());
            origin.setStatus(project.getStatus());

            return origin;

        }, (data) -> {
            // 更新后操作
        });

    }







}
